package com.dd.admin.business.sell.service.impl;

import com.dd.admin.business.memberCard.entity.MemberCard;
import com.dd.admin.business.memberCard.service.MemberCardService;
import com.dd.admin.business.sell.entity.Sell;
import com.dd.admin.business.sell.service.CancelSellService;
import com.dd.admin.business.sell.service.SellService;
import com.dd.admin.business.sellDetail.entity.SellDetail;
import com.dd.admin.business.sellDetail.service.SellDetailService;
import com.dd.admin.common.exception.ApiException;
import com.dd.admin.common.utils.BigDecimalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

import static com.dd.admin.business.pay.enmus.CashierExceptionEnum.CARD_AMOUNT_CHANGE;
import static com.dd.admin.business.pay.enmus.CashierExceptionEnum.PAY_SELL_CARD_AMOUNT_NOT_SUFFICIENT_FUNDS;


@Service
@Slf4j
public class CancelMemberChargedCard implements CancelSellService {
    @Autowired
    MemberCardService memberCardService;
    @Autowired
    SellDetailService sellDetailService;
    @Autowired
    SellService sellService;
    @Override
    public void cancel(Sell sell) {
        Sell extraSellInfo = sellService.getById(sell.getSellId());
        //消费时用的哪张会员卡
        MemberCard memberCard = memberCardService.getById(extraSellInfo.getMemberCardId());

        List<SellDetail> sellDetailList = sellDetailService.selectSellDetailList(sell.getSellId());
        SellDetail sellDetail  = sellDetailList.get(0);

        BigDecimal sellCardAmount = sellDetail.getAmount();
        BigDecimal sellCardGiveAmount = sellDetail.getGiveAmount();

        BigDecimal cardAmount = memberCard.getAmount();
        log.info("当前卡余额:"+cardAmount);
        BigDecimal cardGiveAmount = memberCard.getGiveAmount();
        log.info("当前卡余额:"+cardAmount);

        //消费后余额
        BigDecimal nowCardAmount = BigDecimalUtil.sub(cardAmount,sellCardAmount);
        BigDecimal nowGiveAmount =  BigDecimalUtil.sub(cardGiveAmount,sellCardGiveAmount);

        if (nowCardAmount.signum() == -1|nowGiveAmount.signum() == -1) {
            throw new ApiException(PAY_SELL_CARD_AMOUNT_NOT_SUFFICIENT_FUNDS);
        }

        //修改当前卡金赠送金
        memberCard.setAmount(nowCardAmount);
        memberCard.setGiveAmount(nowGiveAmount);
        Boolean b = memberCardService.updateById(memberCard);
        if(!b){
            throw new ApiException(CARD_AMOUNT_CHANGE);
        }
    }
}
